package StudyCode.summary.zipfile;

import java.io.BufferedInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class DeterminesWhetherTheSpecifiedStream {
	public static InputStream detectCompression(InputStream stream)
			throws IOException {
		InputStream buffered;
		if (stream.markSupported())
			buffered = stream;
		else
			buffered = new BufferedInputStream(stream);

		buffered.mark(2);
		int magic = readUShort(buffered);
		buffered.reset();

		InputStream result;
		if (magic == GZIPInputStream.GZIP_MAGIC)
			result = new GZIPInputStream(buffered);
		else
			result = buffered;
		return result;
	}

	private static int readUShort(InputStream in) throws IOException {
		int b = readUByte(in);
		return (readUByte(in) << 8) | b;
	}

	private static int readUByte(InputStream in) throws IOException {
		int b = in.read();
		if (b == -1) {
			throw new EOFException();
		}
		return b;
	}
}
